package com.archermind.style.controller;

import com.alibaba.fastjson.JSONObject;
import com.archermind.style.bean.Icon;
import com.archermind.style.bean.IconType;
import com.archermind.style.interceptor.Auth;
import com.archermind.style.service.IconService;
import com.archermind.style.util.Result;
import com.archermind.style.util.Search;
import com.feng.fengDUtil.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 *@Author 丰建立
 *@Date 2019/1/25 16:43
 * "查看图标","编辑图标","下载图标"
 */
@Auth("查看图标")
@RestController
@RequestMapping(value = "/icon")
public class IconAction {

    @Autowired
    private IconService iconService;




    @RequestMapping(value = "/list")
    public Result listIconType( Page page,Search search) {
        iconService.query(page,search);
        return Result.success(page);
    }

    @RequestMapping(value = "/repairDimension")
    public Result repairDimension( ) {
        try {
            iconService.repairDimension();
            return Result.success();
        } catch (IOException e) {
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping(value = "/listSprite")
    public Result listSprite( Page page,Search search) {
        iconService.listSprite(page,search);
        return Result.success(page);
    }

    @RequestMapping(value = "/existImage")
    public Result existImage( Integer folderId) {
        Long exists = iconService.sql("select 1 from icon where typeId = ? limit 1").one(Long.class,folderId);
        return Result.success(exists);
    }

    @RequestMapping(value = "/getUrl")
    public Result getUrl( @RequestParam(value = "folderId") Integer folderId,@RequestParam(value = "iconName") String iconName) {
        String path = iconService.getIconPath(folderId,iconName);
        return Result.success(path);
    }

    @Auth("编辑图标")
    @RequestMapping(value="/del")
    public Result del(String ids){
        try {
            iconService.delIcons(ids);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    @Auth("编辑图标")
    @RequestMapping(value="/shiftType")
    public Result shiftType(@RequestBody String[] names,Integer iconType){
        try {
            iconService.shiftType(names,iconType);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }


    @Auth("编辑图标")
    @RequestMapping(value="/edit")
    public Result edit(Integer[] ids,String[] names,Integer[] scaleIds){
        try {
            iconService.editIcons(ids,names,scaleIds);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping(value="/checkUniqueName_mute")
    public JSONObject checkUniqueName(@RequestParam(value = "ids",required = true) String ids,
                                      @RequestParam(value = "iconName",required = true) String iconName,
                                      @RequestParam(value = "folderId",required = true) Integer folderId)
    {
        JSONObject ret = new JSONObject();
        ret.put("isUnique",iconService.isUnique(iconName,folderId,ids));
        return ret;
    }


    @RequestMapping(value = "/listIconType")
    public Result listIconType() {
       List<IconType> list = iconService.listIconFolder();
       return Result.success(list);
    }

    @Auth("编辑图标")
    @RequestMapping(value="/saveType")
    public Result save(@RequestBody IconType type){
        try {
            iconService.saveOrUpdate(type);
            return Result.success(type);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }


    @Auth("编辑图标")
    @RequestMapping(value="/delType")
    public Result delType(Integer typeId){
        try {
            iconService.deleteById(IconType.class,typeId);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Auth("编辑图标")
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public Result uploadImg(HttpServletRequest request,Integer folderId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();
        JSONObject data = new JSONObject();
        List<Icon> icons = new ArrayList();
        List<String> names = new ArrayList<>();
        try {
            //循环获取file数组中得文件
            for(Map.Entry<String, List<MultipartFile>> entity:fileMap.entrySet()){
                List <MultipartFile> files = entity.getValue();
                for(MultipartFile file:files){
                    Icon icon = new Icon();
                    String name = file.getOriginalFilename();
                    icon.setName(name);
                    icon.setCreateTime(new Date());
                    names.add(name);
                    iconService.saveImage(file,icon);
                    icon.setTypeId(folderId);
                    icon.setIconType(iconService.getIconType(name).getValue());
                    icons.add(icon);
                }
            }
            List<Icon> existsIcons = iconService.selectExistsIcons(folderId,names);
            if(existsIcons.size()>0){
                List<Integer> idList = new ArrayList<>();
                for(Icon icon:existsIcons){
                    idList.add(icon.getId());
                }
                iconService.delIcons(StringUtils.collectionToCommaDelimitedString(idList));
                data.put("deleteIds",idList);
            }
            iconService.saveOrUpdateAll(icons);
            data.put("icons",icons);
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @Auth("下载图标")
    @RequestMapping(value = "/downloadZip", method = RequestMethod.GET)
    public void downloadZip(HttpServletResponse httpServletResponse, @RequestParam("ids") String ids) throws IOException {
        httpServletResponse.setContentType("application/zip");
        httpServletResponse.setHeader("Content-disposition",
                "attachment; filename=" + new String("icons".getBytes(),"ISO-8859-1") + ".zip");
        OutputStream outputStream = httpServletResponse.getOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

        List<Icon> icons = iconService.getIconByIds(ids);
        int count;
        byte[] buf = new byte[1024];
        for(Icon icon:icons){
            File file = iconService.getIconFile(icon);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

            zipOutputStream.putNextEntry(new ZipEntry(icon.getName()));
            //将源文件写入到zip文件中
            while((count=bis.read(buf))!=-1)
            {
                zipOutputStream.write(buf,0,count);
            }
            bis.close();
        }

        zipOutputStream.flush();
        zipOutputStream.close();

        outputStream.flush();
        outputStream.close();
    }


}